<?php


namespace apps\marriage\core\service;


use apps\marriage\core\model\MatchmakerSpreadSalaryRecord;
use apps\marriage\core\model\UserAccountBook;
use vm\com\BaseService;

class MatchmakerSpreadSalaryRecordService extends BaseService
{

    /**
     * @return MatchmakerSpreadSalaryRecord
     */
    protected function getModel()
    {
        return new MatchmakerSpreadSalaryRecord();
    }

    /**
     * @return BaseService|UserService
     */
    private function getUserService()
    {
        return service('User', SERVICE_NAMESPACE);
    }

    /**
     * @return BaseService|VipLevelOrderService
     */
    private function getVipLevelOrderService()
    {
        return service('VipLevelOrder', SERVICE_NAMESPACE);
    }

    /**
     * @return BaseService|ServiceChargeOrderService
     */
    private function getServiceChargeOrderService()
    {
        return service('ServiceChargeOrder', SERVICE_NAMESPACE);
    }

    /**
     * @return BaseService|CourseOrderService
     */
    private function getCourseOrderService()
    {
        return service('CourseOrder', SERVICE_NAMESPACE);
    }

    /**
     * @return BaseService|ServicePackageOrderService
     */
    private function getServicePackageOrderService()
    {
        return service('ServicePackageOrder', SERVICE_NAMESPACE);
    }

    /**
     * @return BaseService|SiteConfigService
     */
    private function getSiteConfigService()
    {
        return service('SiteConfig', SERVICE_NAMESPACE);
    }

    public function create(array $data)
    {
        $data['dateline'] = time();
        return parent::create($data);
    }

    /**
     * 计算佣金
     * @param $iidType
     * @param $iid
     * @throws \think\Exception
     */
    public function onComputeSalary($iidType, $iid)
    {
        $matchmakerSalaryRatio = $this->getSiteConfigService()->getValueByCode('matchmaker_salary_ratio');
        $userService = $this->getUserService();
        $userId = 0;
        $orderMoney = 0.00;
        $salaryRatio = '';
        $userAccountBookIidType = 0;
        $remark = '';
        if($iidType == MatchmakerSpreadSalaryRecord::IID_TYPE_VIP_LEVEL) {  // 购买会员
            $order = $this->getVipLevelOrderService()->getByPk($iid);
            $userId = $order['user_id'];
            $orderMoney = $order['order_money'];
            $salaryRatio = 'vip_level_';
            $userAccountBookIidType = UserAccountBook::IID_TYPE_VIP_LEVEL;
            $remark = '购买会员';
        } else if(in_array($iidType, [
            MatchmakerSpreadSalaryRecord::IID_TYPE_UNLOCK_MEMBER_PHONE,
            MatchmakerSpreadSalaryRecord::IID_TYPE_UNLOCK_MEMBER_WXID,
            MatchmakerSpreadSalaryRecord::IID_TYPE_FACEID_DETECT,
            MatchmakerSpreadSalaryRecord::IID_TYPE_ACTIVITY,
            MatchmakerSpreadSalaryRecord::IID_TYPE_UNLOCK_CHAT_SESSION
        ])) {   // 服务订单
            $order = $this->getServiceChargeOrderService()->getByPk($iid);
            $userId = $order['user_id'];
            $orderMoney = $order['order_money'];
            if($iidType == MatchmakerSpreadSalaryRecord::IID_TYPE_UNLOCK_MEMBER_PHONE) {
                $salaryRatio = 'unlock_phone_';
                $userAccountBookIidType = UserAccountBook::IID_TYPE_UNLOCK_MEMBER_PHONE;
                $remark = '解锁手机号';
            } else if($iidType == MatchmakerSpreadSalaryRecord::IID_TYPE_UNLOCK_MEMBER_WXID) {
                $salaryRatio = 'unlock_wxid_';
                $userAccountBookIidType = UserAccountBook::IID_TYPE_UNLOCK_MEMBER_WXID;
                $remark = '解锁微信号';
            } else if($iidType == MatchmakerSpreadSalaryRecord::IID_TYPE_FACEID_DETECT) {
                $salaryRatio = 'faceid_detect_';
                $userAccountBookIidType = UserAccountBook::IID_TYPE_FACEID_DETECT;
                $remark = '实名认证';
            } else if($iidType == MatchmakerSpreadSalaryRecord::IID_TYPE_ACTIVITY) {
                $salaryRatio = 'activity_';
                $userAccountBookIidType = UserAccountBook::IID_TYPE_ACTIVITY;
                $remark = '参加活动';
            } else if($iidType == MatchmakerSpreadSalaryRecord::IID_TYPE_UNLOCK_CHAT_SESSION) {
                $salaryRatio = 'unlock_chat_session_';
                $userAccountBookIidType = UserAccountBook::IID_TYPE_UNLOCK_CHAT_SESSION;
                $remark = '解锁聊天';
            }
        } else if($iidType == MatchmakerSpreadSalaryRecord::IID_TYPE_COURSE) {  // 课程
            $order = $this->getCourseOrderService()->getByPk($iid);
            $userId = $order['user_id'];
            $orderMoney = $order['pay_money'];
            $salaryRatio = 'course_';
            $userAccountBookIidType = UserAccountBook::IID_TYPE_COURSE;
            $remark = '购买课程';
        } else if($iidType == MatchmakerSpreadSalaryRecord::IID_TYPE_SERVICE_PACKAGE) {  // 服务套餐
            $order = $this->getServicePackageOrderService()->getByPk($iid);
            $userId = $order['user_id'];
            $orderMoney = $order['order_money'];
            $salaryRatio = 'service_package_';
            $userAccountBookIidType = UserAccountBook::IID_TYPE_SERVICE_PACKAGE;
            $remark = '购买服务套餐';
        }

        $user = $userService->getByPk($userId);
        if($user['fromuid'] > 0) {
            $matchmakerUserIds = explode(',', $user['matchmaker_uids']);
            for ($i = 0; $i < count($matchmakerUserIds); $i++) {
                if($matchmakerUserIds[$i] == $userId) {
                    continue;
                }
                $matchmakerUser = $userService->getByPk($matchmakerUserIds[$i]);
                if($matchmakerUser['is_matchmaker'] == 0) {
                    continue;
                }
                $level = $i + 1;
                $amount = (floatval($matchmakerSalaryRatio[$salaryRatio . $level])/100) * floatval($orderMoney);
                if($amount > 0) {
                    $this->create([
                        'user_id' => $matchmakerUserIds[$i],
                        'amount' => $amount,
                        'iid' => $iid,
                        'iid_type' => $iidType,
                        'remark' => $remark,
                        'dateline' => time()
                    ]);
                    $userService->increaseWithdrawBalance($matchmakerUserIds[$i], $amount, true, '佣金收入', $userAccountBookIidType, $iid);
                }
                if($i == 1) {   // 只计算两级佣金
                    break;
                }
            }
        }
    }

    public function format(array $data)
    {
        $userService = $this->getUserService();
        $order = null;
        $user = null;
        if($data['iid_type'] == MatchmakerSpreadSalaryRecord::IID_TYPE_VIP_LEVEL) {  // 购买会员
            $order = $this->getVipLevelOrderService()->getByPk($data['iid']);
            $user = $userService->getByPk($order['user_id']);
        } else if(in_array($data['iid_type'], [
            MatchmakerSpreadSalaryRecord::IID_TYPE_UNLOCK_MEMBER_PHONE,
            MatchmakerSpreadSalaryRecord::IID_TYPE_UNLOCK_MEMBER_WXID,
            MatchmakerSpreadSalaryRecord::IID_TYPE_FACEID_DETECT,
            MatchmakerSpreadSalaryRecord::IID_TYPE_ACTIVITY,
            MatchmakerSpreadSalaryRecord::IID_TYPE_UNLOCK_CHAT_SESSION
        ])) {
            $order = $this->getServiceChargeOrderService()->getByPk($data['iid']);
            $user = $userService->getByPk($order['user_id']);
        } else if($data['iid_type'] == MatchmakerSpreadSalaryRecord::IID_TYPE_COURSE) {  // 课程
            $order = $this->getCourseOrderService()->getByPk($data['iid']);
            $user = $userService->getByPk($order['user_id']);
        } else if($data['iid_type'] == MatchmakerSpreadSalaryRecord::IID_TYPE_SERVICE_PACKAGE) {  // 服务套餐
            $order = $this->getServicePackageOrderService()->getByPk($data['iid']);
            $user = $userService->getByPk($order['user_id']);
        }
        $user = $user ? arrayOnly($user, ['id', 'nick', 'avatar_url']) : null;
        $data['order'] = $order;
        $data['user'] = $user;
        return $data;
    }

    public function sum($field, array $params = [])
    {
        $model = $this->getModel();
        foreach ($params as $key => $val) {
            if($key == 'begin_time') {
                $model = $model->where('dateline', '>=', $val);
            } else if($key == 'end_time') {
                $model = $model->where('dateline', '<=', $val);
            } else {
                $model = $model->where($key, $val);
            }
        }
        return $model->sum($field);
    }
}